<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use App\Qingwuit\Models\Goods;
use App\Qingwuit\Models\GoodsSku;
use App\Qingwuit\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    public $modelName = 'Goods';
    public $auth = 'users';

    public function index(Request $request)
    {
        $storeId = $this->getService('Store')->getStoreId()['data'];
        $rs = $this->getService('Base')->getPageData($this->modelName, ['store_id'=>$storeId]);
        return $this->handle($rs);
    }

    public function store(Request $request)
    {
        $rs = $this->getService('Goods')->addGoods();
        return $this->handle($rs);
    }

    public function update(Request $request, $id)
    {

        $rs = $this->getService('Goods')->editGoods($id);
        return $this->handle($rs);
    }

    public function show($id)
    {

        $rs = $this->getService('Goods')->getGoodsInfo($id);
        return $this->handle($rs);
    }

    public function destroy($id)
    {
        $storeId = $this->getService('Store')->getStoreId()['data'];
        $idArray = array_filter(explode(',', $id), function ($item) {
            return (is_numeric($item));
        });
        $goodsList = $this->getService('Goods', true)->select('id')->where('store_id', $storeId)->whereIn('id', $idArray)->get();
        if ($goodsList->isEmpty()) {
            return $this->success();
        }
        $goodsId = [];
        foreach ($goodsList as $v) {
            $goodsId[] = $v->id;
        }
        $this->getService('GoodsSku', true)->where('goods_id', $goodsId)->delete();
        $this->getService('Goods', true)->whereIn('id', $goodsId)->delete();
        return $this->success();
    }


    public function updateStatus()
    {
        $goods_id  = \request()->goods_id;
        $type = \request()->type;
//        print_r($type);die;
        $status= \request()->status;
        $goods_stock= \request()->goods_stock;
        if ($type == 1){
            if ($status == 1){
                $attr = GoodsSku::where('goods_id',$goods_id)->get();
                if ($attr->isEmpty()) {
                    return $this->formaterror(__('商品没有规格，不能上架'));
                }
            }
            Goods::where('id',$goods_id)->update(['goods_status'=>$status]);
        }
        if ($type == 2){
            Goods::where('id',$goods_id)->update(['goods_stock'=>$goods_stock]);
        }

           return  $this->success('修改成功');

    }

    public function statistics(){

        $user_id = $this->getUserId('users');

    }



    public function increaseGoods(){
        $user_id = $this->getUserId('users');
        $goodsModel = $this->getService('Goods', true);
        $storeId = Store::where('user_id',$user_id)->first();
        $data = [
            'store_id'              => $storeId->id ?? 0,
            'goods_name'            => request()->goods_name,                         // 商品名
            'goods_subname'         => request()->goods_subname ?? '',                  // 副标题
            'class_name'              => request()->class_name ?? 0,                        // 商品分类
            'class_id'              => request()->class_id ?? 0,                        // 商品分类
            'goods_master_image'    => request()->goods_master_image,                 // 商品主图
            'goods_price'           => abs(request()->goods_price ?? 0),                // 商品价格
//            'goods_weight'          => abs(request()->goods_weight ?? 0),               // 商品重量
            'goods_stock'           => abs(request()->goods_stock ?? 0),                // 商品库存
            'goods_content'         => request()->goods_content ?? '',                  // 商品内容详情
            'goods_status'          => abs(request()->goods_status) ?? 0,               // 商品上架状态
            'goods_images'          => request()->goods_images ,
            'producing_area'        => request()->producing_area,
            'import'                => request()->import,
            'storage_method'        => request()->storage_method,
            'is_recommend'          => request()->is_recommend
        ];
//        dd($data);die;
        try {
            DB::beginTransaction();
            $goodsModel = $goodsModel->create($data);
//            if (is_null(request()->skuList))
            // 规格处理
            if (isset(request()->skuList) && !empty(request()->skuList)) {
                $skuData = [];
                foreach (request()->skuList as $k => $v) {
                    $skuData[$k]['spec_id'] = implode(',', $v['spec_id']); // sku 属性
                    $skuData[$k]['sku_name'] = implode(',', $v['sku_name']); // sku名称
                    $skuData[$k]['goods_price'] = abs($v['goods_price'] ?? 0); // sku价格
//                    $skuData[$k]['goods_market_price'] = abs($v['goods_market_price'] ?? 0); // sku市场价
                    $skuData[$k]['goods_stock'] = abs($v['goods_stock'] ?? 0); // sku库存
//                    $skuData[$k]['goods_weight'] = abs($v['goods_weight'] ?? 0); // sku 重量
                }
                $goodsModel->goods_skus()->createMany($skuData);
            }else{
                return $this->error('规格不能为空');
            }
            DB::commit();
            return $this->format([], __('tip.success'));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->formatError(__('tip.error'), $e->getMessage());
        }
    }
    public function store_classes()
    {
        $user_id = $this->getUserId('users');
//        $user_id = 137;
        $storeId = Store::where('user_id',$user_id)->pluck('id');
//        dd($user_id);
        $rs = $this->getService('StoreClass', true)->where('store_id', $storeId)->first();
        if ($rs && !empty($rs->class_id)) {
            $class_id = [];
            $classId = json_decode($rs->class_id, true);
            foreach ($classId as $v) {
                foreach ($v as $vo) {
                    $class_id[] = intval($vo);
                }
            }
            $class = $this->getService('GoodsClass', true)->whereIn('id', $class_id)->get();
            $data = $this->getService('Tool')->getChildren($class);
            return $this->success($data);
        } else {
            return $this->error('class not found');
        }
    }

    public function goodsList(){
        $user = $this->getUserId('users');
//        $user = 137;
        $status = request()->status;
        $keywords = request()->keywords;
        $store_id = Store::where('user_id',$user)->pluck('id');
//        print_r($store_id);die;
        if ($status == ""){
            $goods = Goods::where('store_id',$store_id)
                ->where('goods_name','like','%'.$keywords.'%')
                ->paginate(request()->per_page ?? 30);;
        }else{
            $goods = Goods::where('store_id',$store_id)
                ->where('goods_status',$status)
                ->where('goods_name','like','%'.$keywords.'%')
                ->paginate(request()->per_page ?? 30);;
        }
        return $this->format($goods);
    }


    public function goodsdetails()
    {
        $goods_id = \request()->goods_id;
        $goods = Goods::where('id',$goods_id)->first();
        return $this->format($goods);
    }

    public function editGoods()
    {
        $goods_id = \request()->goods_id;
        $user_id = $this->getUserId('users');
        $storeId = Store::where('user_id', $user_id)->first();
        $goodsModel = Goods::where('id',$goods_id)->first();
//        dd($goodsModel);die;
//        $goodsModel = $goodsModel->where('store_id', );
//        if ($auth == 'users') $goodsModel = $goodsModel->where('store_id', $storeId->id);
//        $goodsModel = $goodsModel->first();
//        dd($goodsModel);
        // 商品名
        if (isset(request()->goods_name) && !empty(request()->goods_name)) {
            $goodsModel->goods_name = request()->goods_name;
        }
        // 副标题
        if (isset(request()->goods_subname) && !empty(request()->goods_subname)) {
            $goodsModel->goods_subname = request()->goods_subname;
        }
        // 商品分类
        if (isset(request()->class_id) && !empty(request()->class_id)) {
            $goodsModel->class_id = request()->class_id;
        }
        // 商品主图
        if (isset(request()->goods_master_image) && !empty(request()->goods_master_image)) {
            $goodsModel->goods_master_image = request()->goods_master_image;
        }
        // 商品价格
        if (isset(request()->goods_price) && !empty(request()->goods_price)) {

            if (is_numeric(request()->goods_price)) {
                $goodsModel->goods_price = abs(request()->goods_price ?? 0);

            }else {
                return $this->error('商品价格请填写数字');
            }
        }

        // 商品重量
        if (isset(request()->goods_weight) && !empty(request()->goods_weight)) {
            $goodsModel->goods_weight = abs(request()->goods_weight ?? 0);
        }
        // 商品库存
        if (isset(request()->goods_stock) && !empty(request()->goods_stock)) {
            $goodsModel->goods_stock = abs(request()->goods_stock ?? 0);
        }
        // 商品内容详情
        if (isset(request()->goods_content) && !empty(request()->goods_content)) {
            $goodsModel->goods_content = request()->goods_content;
        }
        // 商品图片
        if (isset(request()->goods_images) && !empty(request()->goods_images)) {
            $goodsModel->goods_images = request()->goods_images;
        }
        // 商品图片
        if (isset(request()->producing_area) && !empty(request()->producing_area)) {
            $goodsModel->producing_area = request()->producing_area;
        }
        // 商品图片
        if (isset(request()->import) && !empty(request()->import)) {
            $goodsModel->import  = request()->import;
        }
        // 商品图片
        if (isset(request()->storage_method) && !empty(request()->storage_method)) {
            $goodsModel->storage_method = request()->storage_method;
        }
        // 是否推荐
        if (isset(request()->is_recommend)) {
            $goodsModel->is_recommend = abs(request()->is_recommend ?? 0);
        }
//        die;
//        dd($goodsModel);
        try {
            DB::beginTransaction();
            $goodsModel = $goodsModel->save();
            // 规格处理
            if (isset(request()->skuList) && !empty(request()->skuList)) {
                $skuData = [];
                $skuId = []; // 修改的skuID 不存在则准备删除
                foreach (request()->skuList as $k => $v) {
                    if (isset($v['id']) && !empty($v['id'])) {
                        // 如果ID不为空则代表存在此sku 进行修改
                        $skuId[] = $v['id'];
                        $this->getService('GoodsSku', true)->where('goods_id', $goods_id)->where('id', $v['id'])->update([
                            'spec_id' => implode(',', $v['spec_id']), // sku 属性
                            'sku_name' => implode(',', $v['sku_name']), // sku名称
                            'goods_price' => abs($v['goods_price'] ?? 0), // sku价格
                            'goods_stock' => abs($v['goods_stock'] ?? 0), // sku库存
//                            'goods_weight' => abs($v['goods_weight'] ?? 0), // sku 重量
                        ]);
                    } else {
                        // 否则进行插入数据库
                        $skuData[$k]['spec_id'] = implode(',', $v['spec_id']); // sku 属性
                        $skuData[$k]['sku_name'] = implode(',', $v['sku_name']); // sku名称
                        $skuData[$k]['goods_price'] = abs($v['goods_price'] ?? 0); // sku价格
                        $skuData[$k]['goods_stock'] = abs($v['goods_stock'] ?? 0); // sku库存
//                        $skuData[$k]['goods_weight'] = abs($v['goods_weight'] ?? 0); // sku 重量
                    }
                }
                // 如果ID不为空则代表存在此sku 进行修改
                $skuModel = $this->getService('GoodsSku', true)->where('goods_id', $goods_id);
                if (!empty($skuId)) $skuModel->whereNotIn('id', $skuId)->delete();
                if (empty($skuId)) $skuModel->delete();
                // 新建不存在sku进行插入数据库
                if (!empty($skuData)) {
                    $goodsModel = $this->getService('Goods', true)->find($goods_id);
                    $goodsModel->goods_skus()->createMany($skuData);
                }
            } else {
                return $this->error('规格不能为空');
                // 清空所有sku
//                $this->getService('GoodsSku', true)->where('goods_id', $goods_id)->delete();
            }
            DB::commit();
            return $this->format([], __('tip.success'));
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->formaterror(__('tip.error'), $e->getMessage());
        }
    }
}
